package my.jwds.p846;

import java.util.*;

public class IsNStraightHand {

    public static void main(String[] args) {
        IsNStraightHand obj = new IsNStraightHand();
        int [] nums = {9,13,15,23,22,25,4,4,29,15,8,23,12,19,24,17,18,11,22,24,17,17,10,23,21,18,14,18,7,6,3,6,19,11,16,11,12,13,8,26,17,20,13,19,22,21,27,9,20,15,20,27,8,13,25,23,22,15,9,14,20,10,6,5,14,12,7,16,21,18,21,24,23,10,21,16,18,16,18,5,20,19,20,10,14,26,2,9,19,12,28,17,5,7,25,22,16,17,21,11};
        System.out.println(obj.isNStraightHand(nums,10));
    }

    public boolean isNStraightHand(int[] hand, int groupSize){
        if (hand.length%groupSize != 0)return false;
        if (groupSize==1)return true;
        LinkedHashMap<Integer,Integer> map = new LinkedHashMap<>();
        Arrays.sort(hand);
        for (int num : hand) {
            map.put(num,map.getOrDefault(num,0)+1);
        }
        while(!map.isEmpty()){
            if (map.size() < groupSize)return false;
            Iterator<Map.Entry<Integer,Integer>> head = map.entrySet().iterator();
            Map.Entry<Integer,Integer> start = head.next();
            head.remove();
            int minCount = start.getValue();
            Map.Entry<Integer,Integer> end = null;
            for (int i = 1; i < groupSize; i++) {
                end = head.next();
                if (end.getValue() < minCount) {
                    return false;
                } else if (end.getValue() == minCount) {
                    head.remove();
                } else{
                    end.setValue(end.getValue() - minCount);
                }
            }
            if (start.getKey()+groupSize-1 != end.getKey())return false;

        }
        return true;
    }
}